package com.zy.mydemo.common.exception;

import com.zy.mydemo.common.utils.ResultUtils;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;

/**
 * @Author:zhongyong
 * @Description：
 * @Date：Create in 2020/04/28
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Object defaultErrorHandler(HttpServletRequest req, HttpServletResponse response, Exception err) {
        String questUri = req.getRequestURI();

        //如果是接口目录下的地址,直接返回json
        if (Pattern.matches("/api/.*", questUri)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try {
                PrintWriter writer = response.getWriter();
                writer.write(ResultUtils.error(err.getMessage()).toString());
                writer.flush();
                writer.close();
            } catch (Exception e) {

            }
            return null;
        } else {
            //如果不是就返回页面
            ModelAndView view = new ModelAndView();
            view.addObject("err", err);
            view.setViewName("err");
            return view;
        }
    }
}
